package com.hup.htts.presenter;

import com.hup.htts.config.BeanConfig;
import com.hup.htts.service.GlobalKeyService;
import com.hup.htts.service.GlobalKeyService.KeyHandler;
import com.hup.htts.service.tts.TTSService;
import com.hup.htts.service.tts.TTSService.TTSCallback;
import com.hup.htts.service.tts.jna.VoiceInfo;
import com.hup.htts.util.ClipboardUtil;
import com.hup.htts.view.AppTray;
import com.hup.htts.view.MainWindow;
import com.hup.utils.commons.exception.AppExceptionHandler;
import com.hup.utils.commons.exception.ErrInfo;
import com.hup.utils.commons.start.DialogHelper;
import com.hup.utils.commons.start.SimpleExitHandler;
import com.hup.utils.commons.start.SpringContext;
import com.hup.utils.commons.thread.ThreadUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author hugan
 * @date 2021/9/12
 */
@Log4j2
@Component
public class MainPresenter {

    @Autowired
    private TTSService ttsService;
    private GlobalKeyService globalKeyService;
    private MainWindow mainWindow;
    private AppTray appTray;

    public MainPresenter() {
        SpringContext.getBean(SimpleExitHandler.class).setExitAction(this::doExit);
        globalKeyService = SpringContext.getBean(BeanConfig.GLOBAL_KEY_SERVICE, GlobalKeyService.class);
    }

    public void startUp() {
        //语音模块
        ttsService.setCallback(new TTSCallbackHandler());
        //ttsService.setShowDllDebug(true);
        ttsService.init();
        //
        globalKeyService.setKeyHandler(new MyKeyHandler());
        globalKeyService.startListen();

        //界面
        mainWindow = new MainWindow();
        mainWindow.switchVisible(true);
        appTray = new AppTray();
        appTray.doShow();

        //需要创建mainWindow后才能调用
        ttsService.getVoices();
    }

    public void doExit() {
        log.info("");
        ttsService.doTerminate();
        globalKeyService.doTerminate();
        appTray.doHide();
        ThreadUtil.sleep(500);
        System.exit(0);
    }

    private void onErr(String desc, Throwable e) {
        ErrInfo errInfo = AppExceptionHandler.handle(desc + "错误:\n", e);
        DialogHelper.confirm(errInfo.getErrMsg())
                .title(DialogHelper.ERROR)
                .onTop(true)
                .show();
    }

    private class MyKeyHandler implements KeyHandler {

        private int clipErrCount = 0;

        @Override
        public void onEsc() {
            //log.info("");
            if (!ttsService.isInited()) return;
            ttsService.stop();
        }

        @Override
        public void onCtrlC() {
            if (!ttsService.isInited()) return;
            try {
                String clipboardText = ClipboardUtil.getString();
                clipErrCount = 0;
                if (StringUtils.isBlank(clipboardText)) return;
                //log.info("clipboardText.len={}", clipboardText.length());
                //log.info("clipboardText={}", clipboardText);
                ttsService.speak(clipboardText);
            } catch (IllegalStateException e) {
                /*
                偶然会有异常:cannot open system clipboard;
                屏蔽偶然的异常!最多让用户以为没按到按键
                 */
                log.info("{}", e.getMessage());
                clipErrCount++;
                if (clipErrCount < 2) return;
                onErr("读取粘贴板", e);
            } catch (Throwable e) {
                onErr("读取粘贴板", e);
            }
        }
    }

    private class TTSCallbackHandler implements TTSCallback {

        @Override
        public void onGetVoices(ArrayList<VoiceInfo> voiceInfos) {
            mainWindow.onGetVoices(voiceInfos);
        }

        @Override
        public void onErr(String desc, Throwable e) {
            MainPresenter.this.onErr(desc, e);
        }
    }
}
